import Vue from 'vue'
import VueRouter from 'vue-router'

import login from '../views/login'
import index from '../views/index'
import home from '@/views/index/home'
import ask from '@/views/index/ask'
import video from '@/views/index/video'
import my from '@/views/index/my'
import edit from '@/views/index/edit'

// 导入 store
import store from '@/store'
// 导入 Toast
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: login, name: login },
  {
    path: '/index',
    component: index,
    name: index,
    children: [
      { path: 'home', component: home },
      {
        path: 'ask',
        component: ask,
        meta: {
          needLogin: true
        }
      },
      { path: 'video', component: video },
      {
        path: 'my',
        component: my,
        meta: {
          needLogin: true
        }
      }
    ]
  },
  { path: '/edit', component: edit, name: edit }
]

const router = new VueRouter({
  routes
})

// 添加导航守卫
router.beforeEach((to, from, next) => {
  // console.log(to)
  if (to.meta.needLogin) {
    // 说明需要登录
    const token = store.state.token.token
    if (token) {
      next()
    } else {
      Toast.fail('未登录')
      router.push(`/login?url=${to.path}`)
      next()
    }
  } else {
    next()
  }
})

export default router
